package com.chunxuan.langquan.ui.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.chunxuan.langquan.MainActivity;
import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.VersionInfo;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.AlertUtil;
import com.chunxuan.langquan.support.util.Logg;
import com.chunxuan.langquan.support.util.PackageUtils;
import com.kongzue.kongzueupdatesdk.v3.UpdateUtil;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.AppUtils;
import com.ruitu.arad.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class AboutUsActivity extends Base2Activity {
    private ImageView ivBack;
    private RelativeLayout rlSpecialStatement,rlUsingHelp,rlPrivacyPolicy,rlCheckVersion,rlLogout,rlLogoff;
    private TextView tvVersion;
    private AlertDialog alert,alert1,alert2;// 弹窗
    private View alert_view,alert_view1,alert_view2;
    private ProgressBar mProgressBar;
    private volatile boolean mIsCancel = false;
    //  进度
    private int mProgress;
    private TextView tv_downloadnum;
    private Handler handler;
    private UpdateUtil updateUtil;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_about;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ivBack=findViewById(R.id.iv_back);
        rlSpecialStatement=findViewById(R.id.rl_special_statement);
        rlUsingHelp=findViewById(R.id.rl_using_help);
        rlPrivacyPolicy=findViewById(R.id.rl_privacy_policy);
        rlCheckVersion=findViewById(R.id.rl_check_version);
        tvVersion=findViewById(R.id.tv_version);
        tvVersion.setText("v"+AppUtils.getAppVersionName());
        rlLogout=findViewById(R.id.rl_logout);
        rlLogoff=findViewById(R.id.rl_logoff);
        handler = new Handler();
//        rlLogout.setVisibility(View.GONE);
        setOnClickListener(ivBack,rlSpecialStatement,rlUsingHelp,rlPrivacyPolicy,rlCheckVersion,rlLogout,rlLogoff);
        alert = new AlertDialog.Builder(AboutUsActivity.this, R.style.Dialog_FS).create();
        alert1 = new AlertDialog.Builder(AboutUsActivity.this, R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(AboutUsActivity.this, R.style.Dialog_FS).create();
        updateUtil = new UpdateUtil(AboutUsActivity.this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_special_statement:
                startActivity(DeclarationActivity.class);
                break;
            case R.id.rl_using_help:
                startActivity(UsingHelpActivity.class);
                break;
            case R.id.rl_privacy_policy:
                startActivity(PrivacyAgreeActivity.class);
                break;
            case R.id.rl_check_version:
                int vCode= PackageUtils.getVersionCode(AboutUsActivity.this);
                ToastUtils.showShort("已是最新版本");
//                auto_update(AppUtils.getAppVersionName());
                break;
            case R.id.rl_logout:
                showDialog();
                break;
            case R.id.rl_logoff:
                showDialog1();
                break;
        }
    }

    private Disposable auto_update(String vCode) {
        return APIRetrofit.getDefault().checkUpgrade(Global.HEADER,"1",vCode)
                .compose(RxUtil.<BaseResult2<VersionInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<VersionInfo>>() {
                    @Override
                    public void accept(BaseResult2<VersionInfo> result2) throws Exception {
                        if(result2.isSuccess()){
                            if(null==result2.getData().getVersion()){
//                                ToastUtils.showShort("已是最新版本");
                                return;
                            }
                            int versionCode=Integer.valueOf(result2.getData().getVersion().replace(".",""));
                            int vcode=Integer.valueOf(vCode.replace(".",""));
                            Logg.e("====版本号===="+versionCode+"=="+vcode);
                            if(versionCode<=vcode){
//                                ToastUtils.showShort("已是最新版本");
                            }else{
                                showUpdateDialog(result2.getData().getAppfile(),result2.getData().getContent());
                            }
                        } else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
//                        throwable.printStackTrace();
//                        ToastUtils.showShort("已是最新版本");
                    }
                });
    }
    private void showUpdateDialog(String appurl,String content){
        updateUtil.setOnUpdateStatusChangeListener(null)
                .showDownloadNotification("正在更新", "正在下载UpdateV3框架更新...")
                .showDownloadProgressDialog("正在下载", "", "取消")
                .start(appurl,
                        "发现新版本",
                        content,
                        "去更新",
                        "再想想",
                        "",
                        false
                );
    }

//    private Disposable auto_update(String vCode) {
//        return APIRetrofit.getDefault().checkUpgrade(Global.HEADER,"1","1.0.0")
//                .compose(RxUtil.<BaseResult2<VersionInfo>>subIoObMain())
//                .subscribe(new Consumer<BaseResult2<VersionInfo>>() {
//                    @Override
//                    public void accept(BaseResult2<VersionInfo> result2) throws Exception {
//                        if(result2.isSuccess()){
//                            Logg.e("==数据库版本号=="+result2.getData().getVersion());
//                            int versionCode=Integer.valueOf(result2.getData().getVersion().replace(".",""));
//                            int vCode= PackageUtils.getVersionCode(AboutUsActivity.this);
//                            Logg.e("====版本号===="+versionCode+"=="+vCode);
//                            if(versionCode<=vCode){
//                                ToastUtils.showShort("已是最新版本");
//                            }else{
//                                showUpdateDialog();
//                            }
//                        } else{
//                            ToastUtils.showShort(result2.getMsg());
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
////                        hideProgress();
//                        throwable.printStackTrace();
////                        ToastUtils.showShort("退出登录失败");
//                    }
//                });
//    }

    private void showUpdateDialog() {
        alert2.show();
        alert2.setCancelable(false);
        alert_view2 = View.inflate(AboutUsActivity.this, R.layout.layout_alert_video_pop_alert, null);
        TextView tv_title = alert_view2.findViewById(R.id.tv_title);
        tv_title.setText("检测到新版本");
        TextView tv_Confirm = alert_view2.findViewById(R.id.tv_2);
        tv_Confirm.setText("立即更新");
        TextView tv_Cancel = alert_view2.findViewById(R.id.tv_1);
        tv_Cancel.setText("以后再说");
        alert_view2.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
            }
        });
        alert_view2.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDownloadDialog();
                alert2.dismiss();
            }
        });
        AlertUtil.setAlertCenterStyle(alert2.getWindow(), alert_view2, AboutUsActivity.this);
    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(AboutUsActivity.this);
        builder.setTitle("下载中");
        View view = LayoutInflater.from(AboutUsActivity.this).inflate(R.layout.dialog_progress, null);
        mProgressBar = view.findViewById(R.id.progressBar);
        builder.setView(view);

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 隐藏当前对话框
                dialog.dismiss();
                // 设置下载状态为取消
                mIsCancel = true;
            }
        });

//        mDownloadDialog = builder.create();
//        mDownloadDialog.show();

        // 下载文件
//        downloadAPK();
    }
//    private void downloadAPK() {
//        File file=new File(download);
//        if(!file.exists()){
//            file.mkdirs();
//        }
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    mIsCancel = false;
//                    // 下载文件
//                    String url="https://langquanedu.oss-cn-beijing.aliyuncs.com/apk/langquantongxue.apk";
//                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//                    conn.connect();
//                    InputStream is = conn.getInputStream();
//                    int length = conn.getContentLength();
//                    // url_version + ".apk",自己定义的apK名称
//                    File apkFile = new File(download, url_version + ".apk");
//                    FileOutputStream fos = new FileOutputStream(apkFile);
//
//                    int count = 0;
//                    byte[] buffer = new byte[1024];
//
//                    while (!mIsCancel) {
//                        int numread = is.read(buffer);
//                        count += numread;
//                        // 计算进度条的当前位置
//                        mProgress = (int) (((float) count / length) * 100);
//                        // 更新进度条
//                        init_message(68, String.valueOf(mProgress));
//
//                        // 下载完成
//                        if (numread < 0) {
//                            handler.sendEmptyMessage(69);
//                            break;
//                        }
//                        fos.write(buffer, 0, numread);
//                    }
//                    fos.close();
//                    is.close();
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }

    //线程
    private void init_message(int num, String str) {
        Message message = handler.obtainMessage();
        message.what = num;
        message.obj = str;
        handler.sendMessage(message);
    }

    public void showDialog1() {// 弹窗
        alert1.show();
        alert1.setCancelable(false);
        alert_view1 = View.inflate(AboutUsActivity.this, R.layout.layout_alert_video_pop_alert, null);
        TextView tv_title = alert_view1.findViewById(R.id.tv_title);
        tv_title.setText("确定要注销账号?");
        TextView tv_Confirm = alert_view1.findViewById(R.id.tv_2);
        tv_Confirm.setText("确定");
        TextView tv_Cancel = alert_view1.findViewById(R.id.tv_1);
        tv_Cancel.setText("取消");
        alert_view1.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert1.dismiss();
            }
        });
        alert_view1.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logoff();
                alert1.dismiss();
            }
        });
        AlertUtil.setAlertCenterStyle(alert1.getWindow(), alert_view1, AboutUsActivity.this);
    }
    private Disposable logoff() {
        return APIRetrofit.getDefault().logoff(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        if(result2.isSuccess()){
                            ToastUtils.showShort(result2.getMsg());
                            Arad.preferences.putString(Config.USER_PREF_KEY, "").flush();
                            Arad.preferences.putString(Config.PASSWORD_PREF_KEY, "").flush();
                            Global.HEADER="";
                            Arad.preferences.putInteger("LOGIN_TYPE",0).flush();
                            Arad.preferences.putBoolean("editGradeSuccess",false).flush();
                            startActivity(LoginActivity.class);
                            ActiviceCollector.finishAll();
                            finish();
                        } else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("注销账号失败");
                    }
                });
    }
    public void showDialog() {// 弹窗
        alert.show();
        alert.setCancelable(false);
        alert_view = View.inflate(AboutUsActivity.this, R.layout.layout_alert_video_pop_alert, null);
        TextView tv_title = alert_view.findViewById(R.id.tv_title);
        tv_title.setText("确定要退出登录?");
        TextView tv_Confirm = alert_view.findViewById(R.id.tv_2);
        tv_Confirm.setText("确定");
        TextView tv_Cancel = alert_view.findViewById(R.id.tv_1);
        tv_Cancel.setText("取消");
        alert_view.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        alert_view.findViewById(R.id.tv_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
                alert.dismiss();
            }
        });
        AlertUtil.setAlertCenterStyle(alert.getWindow(), alert_view, AboutUsActivity.this);
    }
    private Disposable logout() {
        return APIRetrofit.getDefault().logout(Global.HEADER,"")
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        if(result2.isSuccess()){
                            ToastUtils.showShort(result2.getMsg());
                            Arad.preferences.putString(Config.USER_PREF_KEY, "").flush();
                            Arad.preferences.putString(Config.PASSWORD_PREF_KEY, "").flush();
                            Global.HEADER="";
                            Arad.preferences.putInteger("LOGIN_TYPE",0).flush();
//                            Arad.preferences.putBoolean("editGradeSuccess",false).flush();
                            startActivity(LoginActivity.class);
                            ActiviceCollector.finishAll();
                            finish();
                        } else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("退出登录失败");
                    }
                });
    }

}
